package cn.hn.tx.mail.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hn.comm.LocalFiles;
import cn.hn.comm.ibatis.BaseDAO;
import cn.hn.net.Kit;
import cn.hn.tx.mail.model.MailCrawlURL;
import cn.hn.tx.mail.service.IMailCrawlService;

public class MailCrawlServiceImpl implements IMailCrawlService {

	final String NAMESPACE = "cn.hn.tx.mail.dao";

	private String regexMail = "[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+";

	// DAO基类
	private BaseDAO baseDAO;

	public static void main(String[] args) {
		MailCrawlServiceImpl mcs = new MailCrawlServiceImpl();
		List<String> listMail=
		mcs.crawlMail("http://www.tianya.cn/publicforum/content/music/1/145295.shtml");
		
		for(String mail:listMail)
		{
			System.out.println(mail);
		}
		
	}

	public boolean hasExistUrl(String url) {
		Integer count = queryMailCrawlURLCountByURL(url);
		if (null != count && count > 0) {
			return true;
		}
		return false;
	}

	public void insertMailCrawlURL(MailCrawlURL mailCrawlURL) {
		baseDAO.insert(NAMESPACE, "insertMailCrawlURL", mailCrawlURL);
	}

	public void updateMailCrawlURL(MailCrawlURL mailCrawlURL) {
		baseDAO.update(NAMESPACE, "updateMailCrawlURL", mailCrawlURL);
	}

	public MailCrawlURL queryMailCrawlURLById(Integer id) {
		return (MailCrawlURL) baseDAO.query(NAMESPACE, "queryMailCrawlURLById",
				id);
	}

	public Integer queryMailCrawlURLCountByURL(String url) {
		return (Integer) baseDAO.query(NAMESPACE,
				"queryMailCrawlURLCountByURL", url);
	}

	public MailCrawlURL queryMailCrawlURLByURL(String url) {
		return (MailCrawlURL) baseDAO.query(NAMESPACE,
				"queryMailCrawlURLByURL", url);
	}

	public List<String> crawlMail(String url) {


		List<String> listMail = new ArrayList<String>();
		
//		LocalFiles lf = new LocalFiles();
//		String html = lf.readTxtFile("D:" + File.separator + "mail.txt");
		
		String html = Kit.httpRequest(url, null, "GET", "gb2312");	
		
		// System.out.println(html);

		Pattern p = Pattern.compile(regexMail);
		Matcher m = p.matcher(html);
		String mail = null;
		while (m.find()) {
			// System.out.println(m.group());
			mail = m.group().trim();
			if (!listMail.contains(mail)) {
				listMail.add(mail);
			}
		}

		return listMail;
	}

	public String getRegexMail() {
		return regexMail;
	}

	public void setRegexMail(String regexMail) {
		this.regexMail = regexMail;
	}

	public BaseDAO getBaseDAO() {
		return baseDAO;
	}

	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}

}
